from fastapi import APIRouter, HTTPException, Depends
from typing import List
from sqlalchemy.orm import Session
from schema import Farm_schema
from controller import Farm_controller
from database.db_init import get_db


router = APIRouter()


@router.post("/Farm", response_model=Farm_schema.Farm, tags=["Farm"])
async def create_Farm(Farm: Farm_schema.Farm, db: Session = Depends(get_db)):
    return Farm_controller.create_Farm(db, Farm)


@router.get("/Farm/{ID}", response_model=Farm_schema.Farm, tags=["Farm"])
async def get_Farm(ID: int, db: Session = Depends(get_db)):
    db_Farm = Farm_controller.get_Farm(db, ID)
    if db_Farm is None:
        raise HTTPException(status_code=404, detail="Farm not found")
    return db_Farm


@router.get("/Farm", response_model=List[Farm_schema.Farm], tags=["Farm"])
async def get_all_Farm(db: Session = Depends(get_db)):
    all_db_Farm = Farm_controller.get_all_Farm(db)
    if all_db_Farm is None:
        raise HTTPException(status_code=404, detail="0 Farm found, empty table")
    return all_db_Farm


@router.put("/Farm/{ID}", tags=["Farm"])
async def update_Farm(ID: int, field_name: str, field_value: str, db: Session = Depends(get_db)):
    try:
        db_Farm = Farm_controller.update_Farm(db, ID, field_name, field_value)
        if db_Farm is None:
            raise HTTPException(status_code=404, detail="Farm not found")
        return db_Farm
    except ValueError as error:
        raise HTTPException(status_code=400, detail=str(error))


@router.delete("/Farm/{ID}", tags=["Farm"])
async def delete_Farm(ID: int, db: Session = Depends(get_db)):
    is_deleted = Farm_controller.delete_Farm(db, ID)
    if is_deleted is None:
        raise HTTPException(status_code=404, detail=f'Sample {ID} does not exist in database')
    else:
        return {'message': f'Successfully delete sample {ID}'}
